﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using System.Net;
using ASPItalia.ModelVirtualCasting.WPF.Common.Helpers;
using System.Diagnostics;

namespace ASPItalia.ModelVirtualCasting.WPF.Models
{
    public class MultimediaImage : Multimedia
    {

        private Stream stream;
        private BitmapSource _imageSource;

        protected MultimediaImage()
        {

        }

        public MultimediaImage(byte[] data)
        {
            CreateImage(new MemoryStream(data));
        }

        protected void CreateImage(Stream ostream)
        {
            stream = new MemoryStream();
            ostream.CopyTo(stream);
            stream.Position = 0;

            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.DecodePixelWidth = 120;
            image.StreamSource = stream;
            image.CreateOptions = BitmapCreateOptions.None;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.EndInit();

            this.SmallImageSource = image;
        }

        public BitmapSource SmallImageSource
        {
            get;
            private set;
        }

        public BitmapSource ImageSource
        {
            get
            {
                if (_imageSource == null)
                {
                    stream.Position = 0;
                    _imageSource = BitmapFrame.Create(stream);
                }
                return _imageSource;
            }
            set
            {
                _imageSource = value;
                OnPropertyChanged("ImageSource");
            }
        }
    }

    public class DesignMultimediaImage : MultimediaImage
    {

        public DesignMultimediaImage()
        {
            
        }

        public Uri UriSource
        {
            set
            {
                try
                {
                    Debug.WriteLine(value);
                    CreateImage(WebRequest.Create(value).GetResponse().GetResponseStream());
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
    }
}
